const mongoose = require('mongoose')
const AdminUser = mongoose.model('adminUser')
const bcrypt = require('bcrypt-nodejs')
const jwt = require('jsonwebtoken')
const config = require('../../config')
const { formatBody, parseToken } = require('../../tools')

module.exports = {
  async login (ctx) {
    let { userName, password } = ctx.request.body
    if (!userName || !password) {
      return ctx.body = formatBody(0, '用户名和密码不可为空')
    }
    let adminUser = await AdminUser.findOne({ userName: userName })
    if (!adminUser) return ctx.body = formatBody(0, '不存在该用户')
    if(bcrypt.compareSync(password, adminUser.password)) {
      let exp = Math.floor((new Date().getTime())/1000) + 60 * 60 * 24
      let token = await jwt.sign({ uid: adminUser._id, exp }, config.server.SIGN_KEY )
      return ctx.body = formatBody(1, '登陆成功', {
        token
      })
    }
    return ctx.body = formatBody(0, '密码错误')
  },
  async logout (ctx) {
    return ctx.body = formatBody(1, 'ok')
  },
  async userInfo (ctx) {
    let { token } = ctx.request.body
    await parseToken(token).then(async data => {
      let { uid } = data
      let adminUser = await AdminUser.findOne({ _id: uid })
      if (adminUser) {
        let { _id, userName, email, avatar, roles } = adminUser
        return ctx.body = formatBody(1, 'ok', {
          _id, email, avatar, roles, name: userName
        })
      } else {
        return ctx.body = formatBody(0, '用户不存在')
      }
    }).catch(err => {
      return ctx.body = formatBody(-1, '登陆已过期', err)
    })
  }
}